<template>
  <div class="table_container">
    <div class="table_top_btn">
      <div class="left_btn">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="openAddOrEdit(['receive', 'add'], {})"
          >{{ t("button.add") }}</el-button
        >
      </div>

      <right-toolbar
        ref="rightToolBarRef"
        @queryTable="queryList"
        :searchConfig="searchConfig"
        :columns.sync="columns"
        @search="handleSearch"
      >
      </right-toolbar>
    </div>

    <div class="table_area">
      <el-table
        height="100%"
        v-loading="loading"
        :data="receiveData"
        :header-cell-style="{ textAlign: 'center' }"
        :cell-style="{ textAlign: 'center' }"
      >
        <el-table-column
          :label="t('tableColumns.operation')"
          align="center"
          fixed
          width="240"
        >
          <template #default="{ row }">
            <div class="operate_link_btn">
              <el-link
                type="primary"
                :underline="false"
                :icon="Document"
                @click="startApply(row)"
                :disabled="
                  row.enableFlag == 1 || row.enableFlag == 3 || row.enableFlag == 4
                    ? false
                    : true
                "
                >{{ t("button.apply") }}</el-link
              >

              <el-link
                type="warning"
                :underline="false"
                :icon="Edit"
                @click="openAddOrEdit(['receive', 'edit'], row)"
                :disabled="
                  row.enableFlag == 1 || row.enableFlag == 3 || row.enableFlag == 4
                    ? false
                    : true
                "
                >{{ t("button.edit") }}</el-link
              >
              <el-link
                type="danger"
                :underline="false"
                :icon="Delete"
                @click="revokeReceive(row)"
                :disabled="row.enableFlag == 1 || row.enableFlag == 4 ? false : true"
                >{{ t("button.void") }}</el-link
              >
            </div>
          </template>
        </el-table-column>
        <template v-for="(item, index) in columns" :key="item.key">
          <el-table-column
            v-if="item.visible"
            :prop="item.prop"
            :label="t(`tableColumns.${item.langKey}`)"
            :width="item.width"
            :show-overflow-tooltip="true"
          >
            <template #default="{ row }">
              <div
                v-if="item.prop == 'receiveNo'"
                :style="{
                  color: colors.primaryColor,
                  cursor: item.isclick ? 'pointer' : '',
                }"
                @click="openAddOrEdit(['receive', 'detail'], row)"
              >
                {{ row.receiveNo }}
              </div>

              <el-tag
                v-else-if="item.prop == 'enableFlag'"
                :type="
                  row.enableFlag == 0 || row.enableFlag == 3 || row.enableFlag == 4
                    ? 'danger'
                    : row.enableFlag == 1
                    ? 'warning'
                    : row.enableFlag == 2
                    ? 'primary'
                    : 'success'
                "
                >{{
                  filterStatus(row.enableFlag, "documentStatus", "id", "langKey") || "无"
                }}</el-tag
              >
              <span
                v-else-if="
                  item.prop == 'ScheduledReturnDate' || item.prop == 'receiveDate'
                "
              >
                {{ parseTime(row[item.prop], "{y}-{m}-{d}") || "无" }}
              </span>
              <span v-else>{{ row[item.prop] || "无" }}</span>
            </template>
          </el-table-column>
        </template>
      </el-table>
    </div>
    <div class="pagination-area">
      <pagination
        :total="page.total"
        v-model:page="page.pageNum"
        v-model:limit="page.pageSize"
        @pagination="queryList"
      />
    </div>
    <addOrEdit
      v-if="operate.openObj.visible"
      ref="addOrEditDialogRef"
      v-model:add-edit-info="operate"
      @getCanUseAssetsData="queryCanUseAssetsData"
      @submitAddEditInfo="submit"
      @cancelAddEditInfo="cancel"
    ></addOrEdit>
  </div>
</template>

<script setup name="reciveTable">
import { useI18n } from "vue-i18n";
const { t } = useI18n();
import colors from "@/assets/styles/variables.module.scss";
import { Edit, Document, Delete } from "@element-plus/icons-vue";
import RightToolbar from "@/components/RightToolbar";

import addOrEdit from "@/components/AshDialog/addOrEdit.vue";
import { receiveColums } from "@/utils/table/columns";
import { documentStatus } from "@/utils/statuData";
import {
  getAssetsReceiveList,
  AddAssetsReceive,
  getAssetsReceiveDetail,
  getAssetsCanReceive,
  ReceiveAssetsRevoke,
} from "@/api/assetsManage/receiveAndBack";
import { AddDocumentApply } from "@/api/assetsManage/apply";
import { GetOrganizationTreeAll } from "@/api/assetsManage/organization";
import { GetUserInfoAll } from "@/api/sys/user";
import { getUserInfo } from "@/utils/auth";
import { ElMessage, ElMessageBox } from "element-plus";
const { proxy } = getCurrentInstance();

const { AssetClassification } = proxy.useDict("AssetClassification");

const receiveData = ref([]); //领用列表
const loading = ref(false);
const columns = receiveColums;
const page = reactive({
  total: 0,
  pageNum: 1,
  pageSize: 100,
});
const users = ref([]);
const organizes = ref([]);
const selectedOrganization = ref(null);
const dates = ref(proxy.getDefault30DaysRange());
const searchConfig = ref({
  form: {
    Dates: dates.value ? dates.value : ["", ""],
  },
  formItems: [
    {
      label: t("assetsList.assetCode"),
      prop: "assetsCode",
      type: "el-input",
      attrs: {
        clearable: true,
        placeholder: t("assetsList.assetCodePlaceholder"),
      },
    },
    {
      label: t("assetsList.assetName"),
      prop: "assetsName",
      type: "el-input",
      attrs: {
        clearable: true,
        placeholder: t("assetsList.assetNamePlaceholder"),
      },
    },
    {
      label: t("assetsList.assetType"),
      prop: "assetsClassifyId",
      type: "el-select",
      attrs: {
        clearable: true,
        placeholder: t("assetsList.assetTypePlaceholder"),
      },
      options: AssetClassification,
      optionProps: {
        key: "dictionaryKey",
        label: "dictionaryName",
        value: "dictionaryCode",
      },
      events: {},
    },
    {
      label: t("assetsList.model"),
      prop: "specModel",
      type: "el-input",
      attrs: { clearable: true, placeholder: t("assetsList.modelPlaceholder") },
    },
    {
      label: t("assetsList.useUser"),
      prop: "useUserName",
      type: "el-input",
      attrs: {
        clearable: true,
        placeholder: t("assetsList.userInputPlaceholder"),
      },
      events: {},
    },
    {
      label: t("receiveAndBack.receiveDate"),
      prop: "Dates",
      type: "el-date-picker",
      attrs: {
        valueFormat: "YYYY-MM-DD",
        "range-separator": t("common.to"),
        "start-placeholder": t("common.startDate"),
        "end-placeholder": t("common.endDate"),
        clearable: true,
        type: "daterange",
        "default-time": dates.value,
      },
    },
  ],
  rules: {},
});

const canUseAssetsInfo = reactive({
  data: [],
  page: {
    total: 0,
    pageNum: 1,
    pageSize: 100,
  },
  loading: false,
  searchInfo: searchConfig,
}); // 传给孙组件的资产数据
provide("canUseAssetsInfo", canUseAssetsInfo);

//组织点击获取人员
const useOrganizationNodeClick = (node) => {
  selectedOrganization.value = node;
  operate.formInfo.receiveOrganizationId = selectedOrganization.value.value;
  operate.formInfo.useUserId = null;
  queryAllUsers(operate.formInfo.receiveOrganizationId);
  proxy.$refs["addOrEditDialogRef"].$refs["receiveOrganizationTreeSelect"][0].blur();
};

const operate = reactive({
  openObj: {
    visible: false,
    openKey: "", //add edit detail
    openType: "", //维修 报废 退还 领用....
    openTitle: "",
    tableTitle: "",
    addLoading: false, //防止重复提交
  },
  formInfo: {
    receiveOrganizationId: "",
    useUserId: null,
    receiveDate: "",
    ScheduledReturnDate: "",
    receiveRemark: "",
  },
  formItems: [
    {
      label: t("receiveAndBack.receiveOrganization"),
      prop: "receiveOrganizationId",
      type: "el-tree-select",
      span: 12,
      attrs: {
        "check-strictly": true, //任意节点都可以选
        clearable: true,
        // disabled: false,
        placeholder: t("receiveAndBack.receiveOrganizationPlaceholder"),
      },
      options: organizes,
      optionProps: {
        label: "Label",
        children: "children",
        value: "value",
      },
      events: {
        "node-click": (node) => useOrganizationNodeClick(node),
      },
      rules: [
        {
          required: true,
          message: t("receiveAndBack.receiveOrganizationRuleErrorTip"),
          trigger: "change",
        },
      ],
      ref: "receiveOrganizationTreeSelect",
    },
    {
      label: t("assetsList.useUser"),
      prop: "useUserId",
      type: "el-select",
      span: 12,
      attrs: { placeholder: t("assetsList.userPlaceholder") },
      events: {},
      options: users,
      optionProps: {
        key: "userId",
        label: "userName",
        value: "userId",
      },
      filterable: true,
      rules: [
        {
          required: true,
          message: t("assetsList.userPlaceholder"),
          trigger: "change",
        },
      ],
    },
    {
      label: t("receiveAndBack.receiveDate"),
      prop: "receiveDate",
      ref: "receiveDateRef",
      type: "el-date-picker",
      span: 12,
      attrs: {
        type: "date",
        "value-format": "YYYY-MM-DD",
        "disabled-date": (date) => proxy.dateBeforeToday(date),
        clearable: false,
        disabled: true,
        placeholder: t("receiveAndBack.receiveDatePlaceholder"),
      },
      events: {},
      rules: [
        {
          required: true,
          message: t("receiveAndBack.receiveDateRuleErrorTip"),
          trigger: "change",
        },
      ],
    },
    {
      label: t("receiveAndBack.scheduledReturnDate"),
      prop: "ScheduledReturnDate",
      ref: "ScheduledReturnDateRef",
      type: "el-date-picker",
      span: 12,
      attrs: {
        type: "date",
        "value-format": "YYYY-MM-DD",
        "disabled-date": (date) => proxy.dateAfterToday(date, true),
        clearable: false,
        disabled: true,
        placeholder: t("receiveAndBack.scheduledReturnDatePlaceholder"),
      },
      events: {},
      rules: [
        {
          required: true,
          message: t("receiveAndBack.scheduledReturnDateRuleErrorTip"),
          trigger: "change",
        },
      ],
    },
    {
      label: t("receiveAndBack.receiveRemark"),
      prop: "receiveRemark",
      type: "el-input",
      span: 24,
      attrs: {
        clearable: true,
        placeholder: t("receiveAndBack.receiveRemarkPlaceholder"),
      },
      events: {},
    },
  ],

  loadingUser: false,
  tableData: [], //表格数据，添加的时候为空，其他情况为查询赋值
  delList: [],
});

//1111获取列表
const queryList = () => {
  const { Dates, ...rest } = searchConfig.value.form;
  const [StartDate, EndDate] = Dates || ["", ""];
  const params = {
    pagination: page.pageNum - 1,
    pageRow: page.pageSize,
    isInit: true,
    ...rest,
    StartDate,
    EndDate,
  };
  loading.value = true;
  getAssetsReceiveList(params)
    .then((res) => {
      loading.value = false;
      receiveData.value = res.output.output;
      page.total = res.output.count;
    })
    .catch((err) => {
      loading.value = false;
    });
};

//获取人员,必须先选择使用组织
const queryAllUsers = (organizeId) => {
  operate.loadingUser = true;
  GetUserInfoAll({
    subordinateDepartmentId: organizeId,
  })
    .then((res) => {
      users.value = res.output;
      operate.loadingUser = false;
    })
    .catch((err) => {
      users.value = [];
      operate.loadingUser = false;
    });
};

//查询单据详情
const queryAssetsDetail = (receiveId) => {
  getAssetsReceiveDetail({ receiveNo: receiveId }).then((res) => {
    operate.tableData = res.output;
  });
};
//222添加修改相关
const openAddOrEdit = (typeKey, row) => {
  const type = typeKey[0];
  const key = typeKey[1];
  const title =
    key == "add"
      ? t("receiveAndBack.addReceiveDialogTitle")
      : key == "edit"
      ? t("receiveAndBack.editReceiveDialogTitle")
      : t("receiveAndBack.viewReceiveDialogTitle");
  operate.openObj = {
    visible: true,
    openKey: key,
    openType: type,
    openTitle: title,
    tableTitle: t("receiveAndBack.receiveAssets"),
    addLoading: false,
  };

  operate.formInfo = {
    receiveDate: proxy.getNowDate(),
    ...row,
    useUserId: row.useUserId || null,
  };

  operate.tableData = [];
  operate.delList = [];
  if (key != "add") {
    queryAssetsDetail(row.receiveNo);
    if (row.receiveOrganizationId && row.useUserId) {
      queryAllUsers(row.receiveOrganizationId);
    }
  }
};
//发起申请
const startApply = (row) => {
  const params = {
    fieldNo: row.receiveNo,
    fieldType: 0,
  };
  AddDocumentApply(params)
    .then((res) => {
      console.log(res);
      ElMessage({
        message: t("message.approvalStartedSuccess"),
        type: "success",
      });
      queryList();
    })
    .catch((err) => {
      console.error(err);
    });
};

//作废领用单
const revokeReceive = (row) => {
  const params = {
    receiveNo: row.receiveNo,
    userId: JSON.parse(getUserInfo()).userId,
  };
  ElMessageBox.confirm(
    `${t("message.confirmVoidDocument")}:${row.receiveNo}?`,
    t("message.tip"),
    {
      confirmButtonText: t("common.confirm"),
      cancelButtonText: t("common.cancel"),
      type: "warning",
    }
  )
    .then(() => {
      ReceiveAssetsRevoke(params)
        .then((res) => {
          ElMessage({ message: t("message.voidSuccess"), type: "success" });
          queryList();
        })
        .catch((err) => {
          console.log("失败", err);
        });
    })
    .catch(() => {});
};

//获取组织
const queryOrganization = () => {
  GetOrganizationTreeAll("")
    .then((res) => {
      organizes.value = res.output;
    })
    .catch((err) => {
      console.log("组织获取失败", err);
    });
};

//添加领用单的提交
const submit = async (info) => {
  const sub = info.infoSub.map((item, index) => {
    return {
      assetsId: item.assetsId,
      assetsName: item.assetsName,
      rowId: index,
      state: item.state ? item.state : 0,
    };
  });
  const delSub = info.delSub.map((item, index) => {
    return {
      assetsId: item.assetsId,
      assetsName: item.assetsName,
      rowId: index,
      state: item.state,
    };
  });
  if (sub.length == 0) {
    ElMessage({ message: t("common.pleaseSelectAssets"), type: "warning" });
    return;
  }
  operate.openObj.addLoading = true;
  const formAdd = {
    ...info.info,
    createUserId: JSON.parse(getUserInfo()).userId,
    createUser: JSON.parse(getUserInfo()).userName,
  };
  const formEdit = {
    ...info.info,
    updateUserId: JSON.parse(getUserInfo()).userId,
    updateUser: JSON.parse(getUserInfo()).userName,
  };
  let params = {
    Info: operate.openObj.openKey == "add" ? formAdd : formEdit,
    InfoSub: operate.openObj.openKey == "add" ? sub : sub.concat(delSub),
  };
  const msg = operate.openObj.openKey == "add" ? t("button.add") : t("button.edit");

  try {
    await AddAssetsReceive(params).then((res) => {
      ElMessage({
        message: `${t("receiveAndBack.receiveDocument")}:${res.output}${msg}${t(
          "common.success"
        )}`,
        type: "success",
      });
    });
    await cancel();
    await queryList();
  } catch (error) {
    operate.openObj.addLoading = false;
  }
};
//取消添加
const cancel = () => {
  operate.openObj.visible = false;
  users.value = [];
};

///3333高级搜索的
const handleSearch = async (info) => {
  await queryList();
};

//44444444孙组件的列表数据
//获取可领用资产
const queryCanUseAssetsData = () => {
  canUseAssetsInfo.loading = true;
  let params = {
    pagination: canUseAssetsInfo.page.pageNum - 1,
    pageRow: canUseAssetsInfo.page.pageSize,
    isInit: true,
    enableFlag: 0,
    ...canUseAssetsInfo.searchInfo.form,
  };
  getAssetsCanReceive(params)
    .then((res) => {
      canUseAssetsInfo.data = res.output.output;
      canUseAssetsInfo.page.total = res.output.count;
      canUseAssetsInfo.loading = false;
    })
    .catch(() => {
      canUseAssetsInfo.data.value = [];
      canUseAssetsInfo.loading = false;
    });
};

onMounted(() => {
  queryList();
  queryOrganization();
});
</script>
<style lang="scss" scoped>
.table_container {
  padding: 0;
}
</style>
